﻿using System.Data;
using MySql.Data.MySqlClient;
using Dapper;
using Microsoft.Extensions.Configuration;
namespace MyFramework.DB
{
    public class MysqlContext
    {
        
        private static IDbConnection uniqueInstance;
        // 定义一个标识确保线程同步
        private static readonly object locker = new object();
        private MysqlContext()
        {
        }
        public static IDbConnection GetInstance()
        {
            // 当第一个线程运行到这里时，此时会对locker对象 "加锁"，
            // 当第二个线程运行该方法时，首先检测到locker对象为"加锁"状态，该线程就会挂起等待第一个线程解锁
            // lock语句运行完之后（即线程运行完之后）会对该对象"解锁"
            if (uniqueInstance == null)
            {
                lock (locker)
                {
                    if (uniqueInstance == null)
                    {
                        ConfigurationBuilder builder = new ConfigurationBuilder();
                        builder.AddJsonFile("appsetting.json");
                        var config = builder.Build();
                        if (string.IsNullOrEmpty(config["connectionstring"]))
                        {
                            throw new SyntaxErrorException("错误的配置！");
                        }
                        uniqueInstance = new MySqlConnection(config["connectionstring"]);
                    }
                }
               
                   
            }
            return uniqueInstance;
        }
        public static IDbConnection GetMulInstance()
        {
            // 当第一个线程运行到这里时，此时会对locker对象 "加锁"，
            // 当第二个线程运行该方法时，首先检测到locker对象为"加锁"状态，该线程就会挂起等待第一个线程解锁
            // lock语句运行完之后（即线程运行完之后）会对该对象"解锁"
            
                        ConfigurationBuilder builder = new ConfigurationBuilder();
                        builder.AddJsonFile("appsetting.json");
                        var config = builder.Build();
                        if (string.IsNullOrEmpty(config["connectionstring"]))
                        {
                            throw new SyntaxErrorException("错误的配置！");
                        }
                        
                 
            
            return new MySqlConnection(config["connectionstring"]);
        }
    }
}
